<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>06_列表渲染_过滤与排序</title>
  </head>
  <body>
    <!--
      1. 列表过滤
      2. 列表排序
      -->
    <div id="app">
      <input type="text" placeholder="请输入搜索内容" v-model="searchName" />
      <ul>
        <li v-for="person in updatedPersons" :key="person.id">
          {{person.id}} - {{person.name}} - {{person.age}}
        </li>
      </ul>
      <button @click="orderType = 'asc'">年龄升序</button>
      <button @click="orderType = 'desc'">年龄降序</button>
      <button @click="orderType = 'default'">原本顺序</button>
    </div>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
      new Vue({
        el: "#app",
        data: {
          persons: [
            { id: 1, name: "jack", age: 20 },
            { id: 2, name: "rose", age: 18 },
            { id: 3, name: "tom", age: 22 },
            { id: 4, name: "jerry", age: 19 },
            { id: 5, name: "marry", age: 30 },
            { id: 6, name: "mike", age: 11 },
            { id: 7, name: "john", age: 66 },
            { id: 8, name: "tony", age: 33 },
          ],
          searchName: "",
          // 1 原本顺序  2 升序  3 降序
          // default 原本顺序 asc 升序 desc 降序
          orderType: "default",
        },
        computed: {
          updatedPersons() {
            // 获取参与计算的数据
            const { persons, searchName, orderType } = this;
            // 计算
            /*
              object
                hasOwnProperty
                Object.keys
                Object.values
              function  
                call/apply/bind
              array
                push/shift/splice/sort/forEach...
                map/filter/reduce/some/every/find/includes...
                  map     返回一个新数组，长度不变，值变 
                  filter  返回一个新数组，长度减少，值不变
                  reduce  长度变，值也变
                  some    返回布尔值，有一个为true就是true，所有都是false就是false
                  every   返回布尔值，有一个为false就是false，所有都是true就是true
            */
            // 过滤
            const filterPersons = persons.filter((person) => {
              // 返回值为true会保留下来
              // 返回值为false会过滤掉
              return person.name.indexOf(searchName) !== -1;
            });

            if (orderType === "default") {
              return filterPersons;
            }

            // 排序
            const sortPersons = filterPersons.sort((a, b) => {
              return orderType === "asc" ? a.age - b.age : b.age - a.age;
            });

            // 返回结算结果
            return sortPersons;
          },
        },
      });
    </script>
  </body>
</html>
